/*
 * Copyright 2011 Nicolas Lochet Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy of the License at
 *	
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 */
package org.nicocube.gwt.parser.stepper.matcher.client;

import java.util.HashSet;
import java.util.Set;

import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;

public class RegexTokenMatcher implements TokenMatcher {

	private final Set<Character> firstChars;
	private final RegExp regex;

	public RegexTokenMatcher(String firstSet, String regex) {
		firstChars = new HashSet<Character>();

		int i = 0;
		while (i < firstSet.length()) {

			if (i < firstSet.length()-2 && firstSet.charAt(i+1) == '-' && firstSet.charAt(i+2) > firstSet.charAt(i)) {
				char curChar = firstSet.charAt(i);
				char endChar = firstSet.charAt(i+2);
				for (char c=curChar  ; c<=endChar ; c++) {
					firstChars.add(c);
				}
				i+=3;
			} else {
				firstChars.add(firstSet.charAt(i));
				i++;
			}
		}

		this.regex = RegExp.compile((regex.charAt(0)=='^'? "":"^") + regex,"");
	}

	@Override
	public Set<Character> firstChars() {
		return firstChars;
	}

	@Override
	public Match match(String s) {
		MatchResult match = regex.exec(s);
		if (match != null) {
			return new Match(true,match.getGroup(0).length());
		} else {
			return new Match(false,0);
		}
	}

}
